<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/15
 * Time: 10:48
 */

namespace app\api\model;

use \Exception as E;
use think\facade\Db;
use \think\response\Json;

class CartModel
{
    private static $_table = 'cart'; // 购物车表
    private static $goods = 'goods'; // 商品表

    /**购物车列表
     * @param array $input
     * @return Json
     */
    public static function CartList($input)
    {
        $field = 'a.id as cart_id,a.num,a.cate_id,b.center_id,b.id as goods_id,b.info as goods_info,b.name as goods_name,b.image,b.stock,b.ot_price,b.price,b.act_price,b.is_activity,c.name as unit_name,d.name as center_name';
        try {
            $data = Db::table(self::$_table)->alias('a')
                ->leftJoin(self::$goods . ' b', 'a.goods_id = b.id')
                ->Join('goods_unit c', 'b.unit_id = c.id')
                ->Join('organization d', 'd.id = b.center_id')
                ->where('a.group_id', $input['group_id'])
                ->field($field)
                ->selectOrFail()->toArray();
            return jsonSuccess('获取成功', $data);
        } catch (E $e) {
            return jsonFail('未找到数据');
        }
    }

    /**编辑购物车
     * @param array $input
     * @return Json
     */
    public static function editCart($input)
    {
        $flag = false;
        try {
            $input['goods'] = json_decode($input['goods'], true);
            $userInfo = Db::table('user')->field('is_adopt,group_id')->where('id',$input['uid'])->find();
            if (!$userInfo) return jsonFail('未找到用户信息');
            if($userInfo['is_adopt'] != 1) return jsonFail('暂未通过审核或审核不通过，不能添加购物车');
            if($userInfo['group_id'] != $input['group_id']) return jsonFail('用户所属公司不一致，不能添加购物车');

            // 获取当前购物车信息
            $map = [
                ['group_id', '=', $input['group_id']]
            ];
            $cartInfo = Db::table(self::$_table)->field('id,goods_id,num')->where($map)->select()->toArray();
            $cartGoodsInfos = array_column($cartInfo, null, 'goods_id');
            // 整理需要添加 删除 编辑的数据
            $editGoodsInfos = array_column($input['goods'], null, 'goods_id');
            $insert = [];
            $delete = [];
            $update = [];
            $time = time();
            foreach ($editGoodsInfos as $k => $editGoodsInfo) {
                if ($editGoodsInfo['num'] == 0) {
                    // 删除
                    $delete[] = $k;
                } else if (isset($cartGoodsInfos[$k])) {
                    if ($editGoodsInfo['num'] != $cartGoodsInfos[$k]['num']) {
                        // 编辑
                        $update[] = [
                            'id' => $cartGoodsInfos[$k]['id'],
                            'num' => $editGoodsInfo['num']
                        ];
                    } else {
                        continue;
                    }
                } else {
                    // 添加
                    $insert[] = [
                        'cate_id' => $editGoodsInfo['cate_id'],
                        'uid' => $input['uid'],
                        'role_type' => $input['role_type'],
                        'goods_id' => $k,
                        'num' => $editGoodsInfo['num'],
                        'group_id' => $input['group_id'],
                        'create_time' => $time
                    ];
                }
            }
            if ($insert == [] && $delete == [] && $update == []) return jsonFail('购物车没有改变');
            Db::startTrans();
            $flag = true;
            if ($insert) {
                // 添加
                $insertRtn = Db::table(self::$_table)->insertAll($insert);
                if (!$insertRtn) {
                    Db::rollback();
                    return jsonFail('添加购物车失败');
                }
            }
            if ($delete) {
                // 删除
                $map = [
                    ['group_id', '=', $input['group_id']],
                    ['goods_id', 'in', $delete]
                ];
                Db::table(self::$_table)->where($map)->delete();
            }
            if ($update) {
                // 更新
                $sqlBuild = '';
                foreach ($update as $v) {
                    $sqlBuild .= "union SELECT {$v['id']} AS id, {$v['num']} AS num ";
                }
                $sqlBuild  = '(' . trim($sqlBuild, 'union') . ') s using(id)';
                $table = self::$_table;
                $updateSql = "UPDATE {$table} c JOIN {$sqlBuild} set c.num = s.num";
                $updateRtn = Db::execute($updateSql);
                if ($updateRtn != count($update)) {
                    Db::rollback();
                    return jsonFail('更新购物车失败');
                }
            }
            Db::commit();
            return jsonSuccess('购物车操作成功');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

//    /**加入购物车
//     * @param array $input
//     * @return Json
//     */
//    public static function AddCart($input)
//    {
//        $user = Db::table('user')->where('id',$input['uid'])->value('is_adopt');
//        if($user!=1) return jsonFail('暂未通过审核，不能添加商品');
//        $res = Db::table(self::$_table)->where('role_type',$input['role_type'])->where('group_id',$input['group_id'])->where('uid',$input['uid'])->where('goods_id',$input['goods_id'])->count('id');
//        try {
//            if($res!=0){
//                $status = Db::table(self::$_table)->where('role_type',$input['role_type'])->where('group_id',$input['group_id'])->where('uid',$input['uid'])->where('goods_id',$input['goods_id'])->inc('num',$input['num'])->update();
//                if($status !=0) return jsonSuccess('添加成功');
//            }else{
//                $input['create_time'] = time();
//                $res = Db::table(self::$_table)->insertGetId($input);
//                if ($res != 0) return jsonSuccess('添加成功');
//            }
//            return jsonFail('添加失败');
//        } catch (E $e) {
//            return jsonFail($e->getMessage());
//        }
//    }
//
//    /**删除购物车
//     * @param array $input
//     * @return Json
//     */
//    public static function DelCart($input)
//    {
//        try {
//            $user = Db::table('user')->where('id',$input['uid'])->value('is_adopt');
//            if($user!=1) return jsonFail('暂未通过审核，不能添加商品');
//            $res = Db::table(self::$_table)->where('id', $input['id'])->delete();
//            if ($res != 0) return jsonSuccess('删除成功');
//            return jsonFail('删除失败');
//        } catch (E $e) {
//            return jsonFail($e->getMessage());
//        }
//    }
//
//    /**增加数量
//     * @param array $input
//     * @return Json
//     */
//    public static function NumCart($input)
//    {
//        try {
//            $user = Db::table('user')->where('id',$input['uid'])->value('is_adopt');
//            if($user!=1) return jsonFail('暂未通过审核，不能添加商品');
//            if($input['type']==1){
//                $res = Db::table(self::$_table)->where('id', $input['id'])->where('goods_id', $input['goods_id'])->inc('num')->update();
//            }else if($input['type']==2){
//                $res = Db::table(self::$_table)->where('id', $input['id'])->where('num','>',1)->where('goods_id', $input['goods_id'])->dec('num')->update();
//            }else{
//                return jsonFail('未知类型错误');
//            }
//            if ($res != 0) return jsonSuccess('修改成功');
//            return jsonFail('修改失败');
//        } catch (E $e) {
//            return jsonFail($e->getMessage());
//        }
//    }
    /**购物车商品份数
     * @param array $input
     * @return Json
     */
    public static function CartNum($input)
    {
        $data = Db::table(self::$_table)->where('group_id',$input['group_id'])->count('id');
        return jsonSuccess('获取成功',$data);
    }
}